﻿using System;

namespace ttc
{
    class InputArg
    {
        public string projectpath = null;
        public bool help = false;
        public bool init = false;
        public bool verbose = false;
        public bool version = false;
        public static InputArg Parse(string[] args)
        {
            InputArg arg = new InputArg();

            string tag = null;
            for (var i = 0; i < args.Length; i++)
            {
                var str = args[i].ToLower();
                if (tag == null)
                {
                    if (str == "--help")//没参数的tag，直接搞就是了
                    {
                        arg.help = true;
                    }
                    if (str == "--init")
                    {
                        arg.init = true;
                    }
                    if (str == "--verbose")
                    {
                        arg.verbose = true;
                    }
                    if (str == "--v" || str == "--version")
                    {
                        arg.version = true;
                    }
                    if (str == "--project")//有参数的tag，先记下来
                    {
                        tag = str;
                    }
                }
                else
                {
                    if (tag == "--project")
                    {
                        arg.projectpath = args[i];
                        tag = null;
                    }
                }
            }



            return arg;
        }
    }
    internal class Program
    {
        const string configfile = "ttconfig.json";
        static void Main(string[] args)
        {
            ShowVersion();

            var _arg = InputArg.Parse(args);
            if (_arg.help)
            {
                ShowHelp();
                return;
            }

            if (_arg.init)
            {
                InitConfigFile();
                return;
            }
            if (_arg.version)
            {
                ShowVersion();
                return;
            }
            //当前目录
            var workdir = System.IO.Directory.GetCurrentDirectory();
            Console.WriteLine("CurDir=" + workdir);
            if (_arg.projectpath == null)
            {

                var file = System.IO.Path.Combine(workdir, configfile);
                //在当前目录下，查找ttconfig.json
                if (System.IO.File.Exists(file) == false)
                {
                    ShowHelp();
                    return;
                }

                _arg.projectpath = workdir;
            }

            Build(_arg);

        }
        static void Build(InputArg _arg)
        {
            var defcolor = Console.ForegroundColor;
            //build
            ttlang.Compiler.Debug_DumpSrc = false;
            ttlang.Compiler.Debug_DumpAst = _arg.verbose;
            ttlang.Compiler.Debug_DumpResult = _arg.verbose;

            //用这种方式而不是try catch，可以不干扰异常断点
            AppDomain.CurrentDomain.UnhandledException += (s, err) =>
            {
                Console.ForegroundColor = ConsoleColor.Red;
                var excep = err.ExceptionObject as Exception;
                var outstr = "build error.";
                if (excep != null)
                    outstr = "build error:" + excep.Message;

                Console.WriteLine(outstr);
                Console.ForegroundColor = defcolor;
            };
            {
                var cc = ttlang.Compiler.CompileProject(_arg.projectpath);
                //如果出错就不会往下执行
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine("compile succ.");
                Console.ForegroundColor = defcolor;

                //build就算出錯也會執行完
                //所以用log顔色來區分結果
                var r = ttlang.Builders.BuildProject(cc);
                if (r.targetcount == r.succcount)
                    Console.ForegroundColor = ConsoleColor.Green;
                else
                    Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("build " + r.ToString());
                Console.ForegroundColor = defcolor;
            }
        }
        static void ShowVersion()
        {
            Console.WriteLine("TTLang Compiler");
            Console.WriteLine("Version " + ttlang.Info.Version);
            Console.WriteLine();
        }
        static void ShowHelp()
        {
            Console.WriteLine("syntax:ttc [path]");
            Console.WriteLine("");
            Console.WriteLine("examples:");
            Console.WriteLine("\t\t\tttc --project d:\\abc");
            Console.WriteLine("\t\t\tttc");
            Console.WriteLine("\t\t\tttc --verbose");
            Console.WriteLine("\t\t\tttc --project d:\\abc --verbose");
            Console.WriteLine("");
            Console.WriteLine("options:");
            Console.WriteLine("\t\t\t --help:\t\tshow this page.");
            Console.WriteLine("\t\t\t --init:\t\tcreate a ttconfig.json here..");
            Console.WriteLine("\t\t\t --version or --v:\tshow version only.");
            Console.WriteLine("\t\t\t --verbose:\tshow more debug info.");
            Console.WriteLine("\t\t\t --project [path]:\tbuild a special project.");

        }
        static void InitConfigFile()
        {
            var workdir = System.IO.Directory.GetCurrentDirectory();

            string defconfig = @"{
  ""projectName"": ""testproj"",//项目名
  ""type"": ""exe"",//or sharedlib，项目类型
  ""compilerOptions"": {
                ""outputs"": //可以配置多种输出，故此处为数组
    [
      {
                    ""target"": ""C"",
        ""autoBuild"": true, //生成项目文件后是否自动编译
        ""outPath"": ""temp/$PROJECTNAME/"" //$加全大写是替换宏
      }
    ]
  }
        }";
            var filename = System.IO.Path.Combine(workdir, configfile);
            System.IO.File.WriteAllText(filename, defconfig);

            Console.WriteLine("write " + configfile + ".");
        }
    }
}
